import inputCommon from '../../../../mixin/inputCommon'
import _ from 'lodash'

export default {
  name: 'render',
  props: ['config', 'editor'],
  inject: ['rootForm'],
  mixins: [inputCommon],
  data() {
    return {
      value: '',
      effectiveValue: ''
    }
  },
  beforeDestroy() {
    if (this.config.type === 'param') {
      this.observer.removeParamsGetter(this.paramsGetter)
    } else if (this.config.type === 'normal') {
      this.observer.removeFilter(this.filterFn)
    }
  },
  created() {
    this.observer = this.rootForm.dataInterfaceObserverManage.get(this.config.dataInterfaceId)
    if (this.config.type === 'param') {
      this.paramsGetter = () => {
        let obj = {}
        let params = this.config.paramName.split(',')
        params.forEach(one => {
          obj[one] = this.effectiveValue
        })
        return obj
      }
      this.observer.addParamsGetter(this.paramsGetter)
    } else if (this.config.type === 'normal') {
      let filter = (data, filterKeyList) => {
        return data.filter(one => filterKeyList.some(key => {
          let v = _.at(one, key)[0]
          if (!v) {
            return false
          }
          return v.indexOf(this.effectiveValue) > -1
        }))
      }

      this.filterFn = (data) => {
        let filterKeyList = this.config.filterKeys.split(',').map(one => one.trim())
        if (this.config.listKey) {
          let list = _.at(data, this.config.listKey)[0]
          let filteredList = filter(list, filterKeyList)
          _.update(data, this.config.listKey, () => filteredList)
          return data
        }
        return filter(data, filterKeyList)
      }
      this.observer.addFilter(this.filterFn)
    }
  },
  methods: {
    commit() {
      this.effectiveValue = this.value
    },
    blur() {
      return this.config.blurCb && this.getParsedFn('blurCb')()
      // return this.config.blurCb && !!(new Function('__properties', '__row', 'with(__properties) {return (' + this.config.blurCb + ')() }'))(this.rootForm.properties, this.scope)
    },
    focus(event) {
      return this.config.focusCb && this.getParsedFn('focusCb')(event)
    },
    keydown(event) {
      return this.config.keydownCb && this.getParsedFn('keydownCb')(event)
    },
    keyup(event) {
      return this.config.keyupCb && this.getParsedFn('keyupCb')(event)
    },
    input() {
      return this.config.inputCb && this.getParsedFn('inputCb')(this.value)
    }
  }
}
